<template>
  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <a-row :gutter="24">
        <a-col :span="8">
          <p>
            <a-space type="small">
              <a-input-search
                  v-model:value="searchName"
                  placeholder="请输入名称(只支持一级分类)"
                  enter-button="搜索"
                  size="large"
                  style="width: 400px"
                  allow-clear
                  @search="handleSearch"
              />
              <a-button type="primary" @click="add()" size="large">
                新增
              </a-button>
            </a-space>
          </p>
          <a-table
              v-if="docTree"
              :columns="columns"
              :row-key="record => record.id"
              :data-source="docTree"
              :pagination="false"
              size="small"
              :loading="loading"
              :defaultExpandAllRows="true"
          >
            <template #name="{ text, record }">
              {{ record.sort }} {{ text }}
            </template>
            <template v-slot:action="{text,record}">
              <a-space type="small">
                <a-button type="primary" @click="edite(record)" size="small">
                  编辑
                </a-button>
                <a-button type="danger" @click="deleteById(record.id)" size="small">
                  删除
                </a-button>
              </a-space>
            </template>
          </a-table>
        </a-col>
        <a-col :span="16">
          <p>
            <a-from layout="inline" :model="param">
              <a-form-item>
                <a-button type="primary" @click="handleSave()">
                  保存
                </a-button>
              </a-form-item>
            </a-from>
          </p>
          <a-form :model="doc" layout="vertical">
            <a-form-item>
              <a-input v-model:value="doc.name" placeholder="名称"/>
            </a-form-item>
            <a-form-item>
              <a-tree-select
                  v-model:value="doc.parent"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="treeSelectData"
                  placeholder="请选择父文档"
                  :replace-fields="{ title: 'name', key: 'id', value: 'id' }"
                  tree-default-expand-all
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item>
              <a-input v-model:value="doc.sort" placeholder="顺序"/>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handlePreviewContent">
                <EyeOutlined/> 内容预览
              </a-button>
            </a-form-item>
            <a-form-item>
              <div id="content"></div>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-drawer width="900" placement="right" :closable="false" :visible="drawerVisible" @close="onDrawerClose">
        <div class="wangeditor" :innerHTML="previewHtml"></div>
      </a-drawer>
    </a-layout-content>
  </a-layout>

  <!--  <a-modal-->
  <!--      title="文档表单"-->
  <!--      v-model:visible="modalVisible"-->
  <!--      :confirm-loading="modalLoading"-->
  <!--      @ok="modalHandleOk"-->
  <!--  >-->
  <!--    <a-form :model="doc" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">-->
  <!--      <a-form-item label="名称">-->
  <!--        <a-input v-model:value="doc.name"/>-->
  <!--      </a-form-item>-->
  <!--      <a-form-item label="父分类">-->
  <!--        <a-tree-select-->
  <!--            v-model:value="doc.parent"-->
  <!--            style="width: 100%"-->
  <!--            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"-->
  <!--            :tree-data="treeSelectData"-->
  <!--            placeholder="请选择父文档"-->
  <!--            :replace-fields="{ title: 'name', key: 'id', value: 'id' }"-->
  <!--            tree-default-expand-all-->
  <!--        >-->
  <!--        </a-tree-select>-->
  <!--      </a-form-item>-->
  <!--      <a-form-item label="顺序">-->
  <!--        <a-input v-model:value="doc.sort"/>-->
  <!--      </a-form-item>-->
  <!--      <a-form-item label="内容">-->
  <!--        <div id="content"></div>-->
  <!--      </a-form-item>-->
  <!--    </a-form>-->
  <!--  </a-modal>-->

</template>

<script lang="ts">
import {defineComponent, onMounted, ref, createVNode} from 'vue';
import axios from 'axios';
import {Tool} from "@/utils/tool";
import {useRoute} from "vue-router";
import {Modal} from 'ant-design-vue';
import {ExclamationCircleOutlined} from '@ant-design/icons-vue';
import E from 'wangeditor'

export default defineComponent({
  name: 'AdminDoc',
  setup() {
    // 获取路由传递的参数
    const route = useRoute();
    let ebookId: any;

    const docs = ref();

    // 表格树形结构
    const docTree = ref();

    // 无限级树结构
    // 因为树选择组件的属性状态，会随当前编辑的节点而变化，所以单独声明一个响应式变量
    const treeSelectData = ref();
    treeSelectData.value = [];

    const loading = ref(false);

    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
        slots: {customRender: 'name'}
      },
      {
        title: '操作',
        key: 'action',
        slots: {customRender: 'action'}
      }
    ];

    // 模态框
    const modalVisible = ref<boolean>(false);
    const modalLoading = ref<boolean>(false);

    // 表单
    const doc = ref();
    doc.value = {
      ebookId: route.query.ebookId,
    };
    let editor = new E('#content')
    // 修改富文本编辑器的z-index
    editor.config.zIndex = 0

    // 搜索
    const searchName = ref();

    /**
     * 修改
     * @param record
     */
    const edite = (record: any) => {

      editor.txt.html("")

      modalVisible.value = true;
      doc.value = record;
      handleQueryContent();

      // 不能选择当前节点及其所有子孙节点，作为父节点，会使树断开
      treeSelectData.value = Tool.copy(docTree.value);
      setDisable(treeSelectData.value, record.id);

      // 为选择树添加一个"无"
      treeSelectData.value.unshift({id: 0, name: '无'});

    };

    const deleteIds: Array<string> = [];
    const deleteNames: Array<string> = [];
    /**
     * 查找整根树枝
     */
    const getDeleteIds = (treeSelectData: any, id: any) => {
      // console.log(treeSelectData, id);
      // 遍历数组，即遍历某一层节点
      for (let i = 0; i < treeSelectData.length; i++) {
        const node = treeSelectData[i];
        if (node.id === id) {
          // 如果当前节点就是目标节点
          console.log("delete", node);
          // 将目标ID放入结果集ids
          // node.disabled = true;
          deleteIds.push(id);
          deleteNames.push(node.name);

          // 遍历所有子节点
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              getDeleteIds(children, children[j].id)
            }
          }
        } else {
          // 如果当前节点不是目标节点，则到其子节点再找找看。
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            getDeleteIds(children, id);
          }
        }
      }
    };

    /**
     * 删除
     * @param record
     */
    const deleteById = (record: any) => {

      Modal.confirm({
        title: () => '你确定要选择删除以下文档吗？',
        icon: () => createVNode(ExclamationCircleOutlined),
        content: () => '被删除后文档将无法恢复',
        onOk() {
          getDeleteIds(docTree.value, record);
          axios.delete("/doc/delete/" + deleteIds.join(","), {
            params: {
              id: record
            }
          }).then((response) => {
            const data = response.data;
            if (data.success) {
              handleQuery({
                name: searchName.value
              });
            }
          });
        },
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        onCancel() {
        },
      });

    };

    /**
     * 新增
     * @param record
     */
    const add = () => {
      editor.txt.html("")

      modalVisible.value = true;
      doc.value = {ebookId: ebookId};

      treeSelectData.value = Tool.copy(docTree.value) || [];

      // 为选择树添加一个"无"
      treeSelectData.value.unshift({id: 0, name: '无'});

    };

    const handleSave = () => {
      modalLoading.value = true;
      doc.value.ebookId = ebookId;
      doc.value.content = editor.txt.html()
      axios.post("/doc/save", doc.value).then((response) => {
        const data = response.data;

        if (data.success) {
          modalVisible.value = false;
          modalLoading.value = false;

          handleQuery({
            name: searchName.value,
            ebookId: ebookId
          });
        }

      });

    }

    /**
     * 搜索框查询
     */
    const handleSearch = () => {
      handleQuery({
        name: searchName.value
      });
    }

    /**
     * 数据查询
     **/
    const handleQuery = (params: any) => {
      loading.value = true;
      // 如果不清空现有数据，则编辑保存重新加载数据后，再点编辑，则列表显示的还是编辑前的数据
      docs.value = [];
      axios.get("/doc/all", {
        params: doc.value
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          docs.value = data.content;
          docTree.value = [];

          docTree.value = Tool.array2Tree(docs.value, 0);
          // 父文档下拉框初始化，相当于点击新增
          treeSelectData.value = Tool.copy(docTree.value) || [];
          // 为选择树添加一个"无"
          treeSelectData.value.unshift({id: 0, name: '无'});
        }
      });
    };

    /**
     * 文档内容查询
     **/
    const handleQueryContent = () => {

      axios.get("/doc/findContent/" + doc.value.id).then((response) => {

        const data = response.data;
        if (data.success) {
          editor.txt.html(data.content);
        }
      });
    };

    /**
     * 将某节点及其子孙节点全部置为disabled
     */
    const setDisable = (treeSelectData: any, id: any) => {
      // console.log(treeSelectData, id);
      // 遍历数组，即遍历某一层节点
      for (let i = 0; i < treeSelectData.length; i++) {
        const node = treeSelectData[i];
        if (node.id === id) {
          // 如果当前节点就是目标节点
          console.log("disabled", node);
          // 将目标节点设置为disabled
          node.disabled = true;

          // 遍历所有子节点，将所有子节点全部都加上disabled
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              setDisable(children, children[j].id)
            }
          }
        } else {
          // 如果当前节点不是目标节点，则到其子节点再找找看。
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            setDisable(children, id);
          }
        }
      }
    };

    // ----------------富文本预览--------------
    const drawerVisible = ref(false);
    const previewHtml = ref();
    const handlePreviewContent = () => {
      const html = editor.txt.html();
      previewHtml.value = html;
      drawerVisible.value = true;
    };
    const onDrawerClose = () => {
      drawerVisible.value = false;
    };

    onMounted(() => {
      ebookId = route.query.ebookId;
      handleQuery({
        ebookId: ebookId
      });
      editor.create();
    });


    return {
      // docs,
      docTree,
      treeSelectData,
      columns,
      loading,
      //模态框
      modalVisible,
      modalLoading,
      edite,
      deleteById,
      handleSave,
      //表单
      doc,
      add,
      toolbar,
      // 搜索
      handleSearch,
      searchName,
      // 富文本预览
      drawerVisible,
      previewHtml,
      handlePreviewContent,
      onDrawerClose,
    }
  }
});
</script>

<style scoped>
img {
  width: 50px;
  height: 50px;
}
</style>
